const initialState = {
  allChanList: [] as ChannelListType,
  currentId: 0,
  userChanList: [] as ChannelListType,
};

export type ChannelListType = {
  id: number;
  name: string;
}[];
// action类型扩展
type ActionProps =
  | { type: 'channel/saveallChanList'; payload: ChannelListType }
  | { type: 'channel/saveUserChanList'; payload: ChannelListType }
  | { type: 'channel/delUserChanList'; payload: number }
  | { type: 'channel/addUserChanList'; payload: ChannelListType }
  | { type: 'channel/changeCurrentId'; payload: number };

export default function channelReducer(
  state = initialState,
  actions: ActionProps
): typeof initialState {
  switch (actions.type) {
    case 'channel/saveallChanList':
      return { ...state, allChanList: [...actions.payload] };
    case 'channel/saveUserChanList':
      return { ...state, userChanList: [...actions.payload] };
    case 'channel/delUserChanList':
      return {
        ...state,
        userChanList: state.userChanList.filter((item) => {
          return item.id !== actions.payload;
        }),
      };
    case 'channel/addUserChanList':
      return {
        ...state,
        userChanList: [...state.userChanList, ...actions.payload],
      };
    case 'channel/changeCurrentId':
      return {
        ...state,
        currentId: actions.payload,
      };
    default:
      return state;
  }
}
